package de.blitzcoder.collide.gui;

import de.blitzcoder.collide.gui.textarea.CollIDETextArea;
import de.blitzcoder.collide.templatemanager.Template;
import de.blitzcoder.collide.templatemanager.TemplateManager;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ListIterator;

/**
 *
 * @author blitzcoder
 */
public class TemplateKeyListener implements KeyListener {

    private CollIDETextArea area;

    public TemplateKeyListener(CollIDETextArea area) {
        this.area = area;
    }


    public void keyPressed(KeyEvent e) {}

    public void keyTyped(KeyEvent e) {}

    public void keyReleased(KeyEvent e) {

        // If tab, try to insert a template
        if (e.getKeyCode() == e.VK_TAB) {

            int pos = area.getLineStartOffset(area.getCaretLine());
            int len = area.getCaretPosition() - pos;

            String origText = area.getBuffer().getText(pos, len);
            String text = origText.replace("\t", "").replace(" ", "");

            if (text.length() != 0) {
                ListIterator<Template> it = Template.getList().listIterator();
                while (it.hasNext()) {
                    Template t = it.next();
                    if (t.getShortcutText().equalsIgnoreCase(text)) {

                        area.getBuffer().beginCompoundEdit();

                        // Remove shortcut and Tab
                        area.getBuffer().remove(pos, len);

                        TemplateManager.startTemplateInsertion(area, t);

                        area.getBuffer().endCompoundEdit();

                        break;
                    }
                }
            }

        }

    }
}
